 //
//  XJPersonSetViewController.m
//  XinJiangMall
//
//  Created by Tzyang on 2018/4/3.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJPersonSetViewController.h"
//controller
#import "XJSetNickNameViewController.h"
#import "XJSetPhoneNumViewController.h"
#import "XJSetRealNameViewController.h"
#import "XJSetLoginPasswdViewController.h"
#import "XJSetPayPasswdViewController.h"
//#import "XJSetReceiptAddressViewController.h"
#import "XJAddressViewController.h"
#import "XJCustomIdentityViewController.h"//7-18

//view
#import "XJPersonSetCell.h"
#import "XJPersonHeaderCell.h"

#import "ZYAlertControl.h"

//相册、相机相关
#import <TZImagePickerController.h>
#import <AVFoundation/AVFoundation.h> // AVCaptureDevice.h 的  AVAuthorizationStatus
#import <QiniuSDK.h>

@interface XJPersonSetViewController ()<UITableViewDataSource,UITableViewDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    /**七牛云上传token*/
    NSString *_token;
    
    //实名认证状态
    NSNumber *_identityState;
}

@property (nonatomic, strong) UITableView * xjps_tableView;
@property (nonatomic, copy) NSArray * xjps_cellArray;

/**目的:用于调取系统相机进行拍照*/
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end

@implementation XJPersonSetViewController
#pragma mark - 一 lazy
- (UIImagePickerController *)imagePickerVc {
    if (!_imagePickerVc) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
//        @property(nullable,nonatomic,weak)      id <UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate;

        _imagePickerVc.delegate = self;
    }
    return _imagePickerVc;
}
#pragma mark - 二 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"个人设置";
    
    self.xjps_tableView.backgroundColor                  = WHITE_COLOR;
    self.xjps_tableView.showsVerticalScrollIndicator     = NO;
    self.xjps_tableView.showsHorizontalScrollIndicator   = NO;
    self.xjps_tableView.dataSource                       = self;
    self.xjps_tableView.delegate                         = self;
    
    [self setExtraCellLineHidden:self.xjps_tableView];
    
    
    //获取七牛云token
    [self requestQiNiuToken];
    [self requestISCustomIdentity];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.xjps_tableView reloadData];
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//   // [self.navigationController setNavigationBarHidden:NO animated:YES];
//    self.tabBarController.tabBar.hidden=YES;    
//}

- (UITableView *)xjps_tableView{
    
    if (!_xjps_tableView) {
        UITableView * xjps_tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
        self.xjps_tableView = xjps_tableView;
        
        [self.view addSubview:xjps_tableView];
    }
    return _xjps_tableView;
    
}


- (NSArray *)xjps_cellArray{
    
    if (!_xjps_cellArray) {
        _xjps_cellArray = @[@[@"头像",@"昵称",@"性别",@"手机号",@"用户编号",@"实名认证"],
                            @[@"登录密码",@"支付密码",@"收货地址"]];
    }
    return _xjps_cellArray;
}


#pragma mark tableView dataSource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.xjps_cellArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  [self.xjps_cellArray[section]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section==0 && indexPath.row ==0) {
        
        XJPersonHeaderCell * xjph_cell = [XJPersonHeaderCell cellWithTableView:tableView];
        xjph_cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [xjph_cell modifyXJPersonHeaderCellIconImg];
    
        //设置头像
        return xjph_cell;
        
    }else{
        XJPersonSetCell * xjps_cell = [XJPersonSetCell cellWithTableView:tableView];
        xjps_cell.selectionStyle = UITableViewCellSelectionStyleGray;
        xjps_cell.titleStr = self.xjps_cellArray[indexPath.section][indexPath.row];
        xjps_cell.showIndicator = YES;
        if (indexPath.section==0 && indexPath.row ==1) {
//            xjps_cell.dataStr = @"张小花";
            xjps_cell.dataStr =  [[NSUserDefaults standardUserDefaults] valueForKey:@"nickname"];
        }
        if (indexPath.section==0 && indexPath.row ==2) {
//            xjps_cell.dataStr = @"女";
            xjps_cell.dataStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"sex"];
        }
        if (indexPath.section==0 && indexPath.row ==3) {
//            xjps_cell.dataStr = @"15588888888";
            xjps_cell.dataStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"phone"];

        }
        if (indexPath.section==0 && indexPath.row ==4) {
            xjps_cell.selectionStyle = UITableViewCellSelectionStyleNone;
            xjps_cell.xjps_indicator.hidden = YES;
            xjps_cell.showIndicator = NO;
//            xjps_cell.dataStr = @"788877665566";
            xjps_cell.dataStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"uuid"];
        }
        if (indexPath.section==0 && indexPath.row ==5) {
            xjps_cell.xjps_detailLab.textColor = XJCOLOR_RGB(244, 67, 54);
//            xjps_cell.dataStr = @"未认证";
            xjps_cell.dataStr = [XJUserModel xj_isIdentifier];
        }
        return xjps_cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0 && indexPath.row==0) {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self setUserIcon];

    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
       
        if (indexPath.section==0 && indexPath.row==1) {//昵称
            XJSetNickNameViewController * setNickVC = [[XJSetNickNameViewController alloc]init];
            [self.navigationController pushViewController:setNickVC animated:YES];
        }else if (indexPath.section==0 && indexPath.row==2){//性别
            
            [self editSexAlert];
        }else if (indexPath.section==0 && indexPath.row==3){//手机号
            XJSetPhoneNumViewController * setPhoneNumVC = [[XJSetPhoneNumViewController alloc]init];
            [self.navigationController pushViewController:setPhoneNumVC animated:YES];
        }else if (indexPath.section==0 && indexPath.row==4){//用户编号
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
        }else if (indexPath.section==0 && indexPath.row==5){//实名认证
            XJCustomIdentityViewController *custonIdVC = [[XJCustomIdentityViewController alloc] init];
            custonIdVC.identityState = _identityState; // 
            
            [self.navigationController pushViewController:custonIdVC animated:YES];
        }else if (indexPath.section==1 && indexPath.row==0){//登录密码
            XJSetLoginPasswdViewController * setLoginPasswdVC = [[XJSetLoginPasswdViewController alloc]init];
            [self.navigationController pushViewController:setLoginPasswdVC animated:YES];
        }else if (indexPath.section==1 && indexPath.row==1){//支付密码
            XJSetPayPasswdViewController * setPayPasswdVC = [[XJSetPayPasswdViewController alloc]init];
            [self.navigationController pushViewController:setPayPasswdVC animated:YES];
        }else if (indexPath.section==1 && indexPath.row==2){//收货地址
//            XJSetReceiptAddressViewController * setAdderssVC = [[XJSetReceiptAddressViewController alloc]init];
            XJAddressViewController * setAdderssVC = [[XJAddressViewController alloc] init];
            [self.navigationController pushViewController:setAdderssVC animated:YES];
        }
        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"%@",self.xjps_cellArray[indexPath.section][indexPath.row]] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0 && indexPath.row==0) {
        return ADAPTHeight(100);
    }else{
        return ADAPTHeight(50);
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section==1) {
        return ADAPTHeight(20);
    }else{
        
        return 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWidth, ADAPTHeight(20))];
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWidth, ADAPTHeight(20))];
    [view addSubview:backView];
    backView.backgroundColor = XJCOLOR_RGB(237, 237, 237);
    return view;
}

//设置分割线
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
        if (indexPath.row < [self.xjps_cellArray[indexPath.section]count]) {
            //四个参数：上左下右
            cell.separatorInset=UIEdgeInsetsMake(0, 10, 0, 10);
        }
    }
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
//隐藏多余分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
}


- (void)setUserIcon{
    [ZYAlertControl showAlertWithTitle:@"请选择上传方式" message:nil statementButtons:@[@"拍照上传",@"从相册选择"] handleBlock:^(NSUInteger btnIndex) {
        XJLog(@"btnIndex == %ld",btnIndex);
        
        if (btnIndex==0) {
            XJLog(@"拍照上传");
            [self takePhoto];
        }else if (btnIndex==1){
            XJLog(@"从相册选择");
            [self configureTzImagePickerVc];
        }
    } cancelButtonTitle:@"取消"];
}



#pragma mark - 修改性别。
- (void)editSexAlert {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请选择性别" preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    UIAlertAction *boyAction  = [UIAlertAction actionWithTitle:@"男" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self requestEditSex:@"男"];
    }];
    UIAlertAction *girlAction = [UIAlertAction actionWithTitle:@"女" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self requestEditSex:@"女"];
    }];
    [alertVC addAction:boyAction];
    [alertVC addAction:girlAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)requestEditSex:(NSString *)sex {
    if ([sex isEqualToString:@"男"]) {
        sex = [NSString stringWithFormat:@"1"];
    }else {
        sex = [NSString stringWithFormat:@"2"];
    }
    [XJHttpTool requestEditPersonMessageWithName:nil sex:sex avator:nil successH:^(id responseObjc) {
        NSNumber *code  = responseObjc[@"code"];
        if ([code isEqualToNumber:@0]) {
            [JRToast showWithText:@"修改成功"];
            
            NSDictionary * dic = responseObjc[@"data"][@"customer"];
            // 保存
            NSNumber *sex = dic[@"sex"];
            if ([sex isEqualToNumber:@1]) {
                [[NSUserDefaults standardUserDefaults] setValue:@"男" forKey:@"sex"];
            }else {
                [[NSUserDefaults standardUserDefaults] setValue:@"女" forKey:@"sex"];
            }
//            [self.navigationController popViewControllerAnimated:YES];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.xjps_tableView reloadData];
        });
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}


#pragma mark - 五 相机相册先关
/// 注意:这里拍照后不保存到本地相册中。
/// 从相册中选择照片
- (void)configureTzImagePickerVc {
    TZImagePickerController *tzIImgpickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    [self presentViewController:tzIImgpickerVc animated:YES completion:nil];
}
//选照片后会走 的代理方法 TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    if(_token.length < 1 ) {
        XJLog(@"获取七牛云token失败 无法上传");
        return;
    }
    
    //选择的图片是
    UIImage *image = [photos lastObject]; // 要取最后一个.取第一个的话每次取出来的都一样
    //上传图片
    [self qiNiuUploadImage:image complete:^(NSString *imgUrl) {

        //使用NSUSerDefault 保存头像的url、将七牛返回的url传给服务器、同时进行界面的刷新
        [self requestEditAvator:imgUrl];
    }];
}


/// 获取相机权限
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        
        NSLog(@"没有相机权限  请在iPhone的""设置-隐私-相机""中允许访问相机");
        
    }else if(authStatus == AVAuthorizationStatusNotDetermined) {
        //如果首次拍照拒绝授权是相机也黑屏情况
        
        NSLog(@"==========");
        //请求获取相机权限
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
    }else {
        NSLog(@"我不要那么多功能");
        
        [self pushImagePickerController];
    }
}


/// 弹出相机进行拍照
- (void)pushImagePickerController {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])) {
        self.imagePickerVc.sourceType = sourceType;
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
        
    }else {
        NSLog(@"模拟器无法打开");
    }
}


/// 使用拍摄的图片的代理回调
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //    NSLog(@"选择了图片:%@",info);
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        XJLog(@"拍照的图片是:%@",image);
        
        // 在这里进行上传图片
        [self qiNiuUploadImage:image complete:^(NSString *imgUrl) {
            //使用NSUSerDefault 保存头像的url、将七牛返回的url传给服务器、同时进行界面的刷新
            [self requestEditAvator:imgUrl];
        }];
    }
}

/// 关闭相机的代理回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    NSLog(@"取消相机");
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -  六 七牛云上传相关
/**获取七牛云token*/
- (void)requestQiNiuToken {
    
    [XJHttpTool requestQiNiuTokenSuccessH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            _token = responseObjc[@"data"][@"token"];
        }
    } fialH:^(NSError *error) {
        XJLog(@"获取七牛云token失败:%@",error);
    }];
}

/**调用七牛云SDK进行图片上传*/
- (void)qiNiuUploadImage:(UIImage *)image complete:(void(^)(NSString *imgUrl))completeBlock {
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];

    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imgName = [NSString stringWithFormat:@"%@.jpg",[self imgNameWithCuttentTime]];
    
    [upManager putData:imageData key:imgName token:_token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        //通过block将七牛返回的结果回调出去
        NSString *imgUrl = resp[@"url"];
        if (completeBlock) {
            completeBlock(imgUrl);
        }
        
    } option:nil];
}

#pragma mark - 七 网络请求(将七牛返回的url回传给服务器)
- (void)requestEditAvator:(NSString *)avator {
    [XJHttpTool requestEditPersonMessageWithName:nil sex:nil avator:avator successH:^(id responseObjc) {
        
        NSNumber *code  = responseObjc[@"code"];
        if ([code isEqualToNumber:@0]) {
            [JRToast showWithText:@"修改成功"];
            
            NSDictionary * dic = responseObjc[@"data"][@"customer"];
            // 保存
            [[NSUserDefaults standardUserDefaults] setValue:dic[@"avatar"] forKey:@"avatar"];
        }
        
        //刷新页面
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.xjps_tableView reloadData];
        });
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

//查看是否进行了实名认证
- (void)requestISCustomIdentity {
    [XJHttpTool requestCustomIsIdentitySuccesH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            NSNumber *status = responseObjc[@"data"][@"identity"][@"status"];
            // 是否实名认证过 //9.
            
            _identityState = status;
            if ([status isEqualToNumber:@1]) { //审核中
                [[NSUserDefaults standardUserDefaults] setValue:@"审核中" forKey:kISIedntifier];
                
            }else if([status isEqualToNumber:@2]){ // 已认证(审核通过)
                [[NSUserDefaults standardUserDefaults] setValue:@"已认证" forKey:kISIedntifier];
                
            }else { //3 未认证
                [[NSUserDefaults standardUserDefaults] setValue:@"未认证" forKey:kISIedntifier];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.xjps_tableView reloadData];
        });
        
    } failH:^(NSError *error) {
        
    }];
}


#pragma mark - 八 Private method
/// 将当前系统时间作为图片的名字
- (NSString *)imgNameWithCuttentTime {
    NSDate *date = [NSDate date];
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString *currentTimeStr = [fmt stringFromDate:date];
    
    return currentTimeStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
